package com.echat.config.filter;

import com.echat.business.home.model.SysUser;
import com.echat.config.common.RequestHolder;
import com.echat.core.constant.CacheKey;
import com.echat.core.utils.redis.JedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @author evan_qb
 * @date 2018/8/29 15:29
 */
@Slf4j
@WebFilter
@Component
public class LoginFilter implements Filter {

    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/oauth/store", "/oauth/token", "/oauth/loginOut", "/user/login")));

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("过滤器初始化。");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String path = req.getServletPath();
        boolean allowedPath = ALLOWED_PATHS.contains(path);
        if (!allowedPath) {
            String authorization = req.getHeader("Authorization");
            if (StringUtils.isNotBlank(authorization)) {
                String access_token = authorization.replaceAll("bearer ", "");
                Object obj = JedisUtil.getObjectValue(CacheKey.USER_KEY + access_token);
                if (obj != null) {
                    SysUser sysUser = (SysUser) obj;
                    //用户为空，则不做任何操作
                    RequestHolder.add(sysUser);
                    RequestHolder.add(req);
                }

            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        log.info("过滤器销毁");
    }
}